/*------------------------------------------------------------------------
* (The MIT License)
* 
* Copyright (c) 2008-2011 Rhomobile, Inc.
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* 
* http://rhomobile.com
*------------------------------------------------------------------------*/

package com.rhomobile.rhodes.util;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.lang.reflect.Method;
import java.util.UUID;

//import com.rhomobile.rhodes.RhoConf;
import com.rhomobile.rhodes.Capabilities;
import com.rhomobile.rhodes.Logger;

/**
 * The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
 * TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
 * on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
 * usable value.
 *
 * In some rare circumstances, this ID may change.  In particular, if the device is factory reset a new device ID
 * may be generated.  In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
 * to a newer, non-buggy version of Android, the device ID may change.  Or, if a user uninstalls your app on
 * a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
 *
 * Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
 * change after a factory reset.  Something to be aware of.
 *
 * Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
 *
 * @see http://code.google.com/p/android/issues/detail?id=10603
 *
 */
public class PhoneId
{
    private static final String TAG = PhoneId.class.getSimpleName();
    //    private static final String CONF_PHONE_ID = "phone_id";
    private String mPhoneId;

    private PhoneId(String phoneId) {
        mPhoneId = phoneId;
    }

    private PhoneId(Context context) throws UnsupportedOperationException {
        String rawId = new String();
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            final String serialNo = (String) get.invoke(c, "ro.serialno");
            rawId += serialNo;
            Logger.I(TAG, "Serial#: " + serialNo);
        } catch (Exception ignored) {
            Logger.W(TAG, "Cannot get proprietary serial number.");
        }
        if (rawId.length() == 0) {

            final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

            // Use the Android ID unless it's broken, in which case fallback on deviceId,
            // unless it's not available, then fallback on a random number.
            if (!"9774d56d682e549c".equals(androidId)) {
                rawId += androidId;
                Logger.I(TAG, "ANDROID_ID: " + androidId);
            } else {
                Logger.W(TAG, "Brocken Android ID, cannot use it: " + androidId);
            }
            if (Capabilities.PHONE_ENABLED) {
                final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                if (deviceId != null && deviceId.length() > 0) {
                    rawId += deviceId;
                    Logger.I(TAG, "Phone device id: " + deviceId);
                } else {
                    Logger.W(TAG, "No telephony service device id.");
                }
            } else {
                Logger.W(TAG, "Phone capability is disabled< cannot access telephony service for its device id.");
            }
//            if (Capabilities.BLUETOOTH_ENABLED) {
//                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//                if (bluetoothAdapter != null) {
//                    final String bluetoothAddr = bluetoothAdapter.getAddress();
//                    if(bluetoothAddr != null && bluetoothAddr.length() > 0) {
//                        rawId += bluetoothAddr;
//                        Logger.D(TAG, "Bluetooth address: " + bluetoothAddr);
//                    }
//                }
//            }
        }
        if (rawId.length() > 0) {
            UUID uuid = UUID.nameUUIDFromBytes(rawId.getBytes());
            mPhoneId = uuid.toString();
            Logger.I(TAG, "Generated phone id: " + mPhoneId);
        } else {
            mPhoneId = "";
        }
    }

    public String getString() {
        return mPhoneId;
    }

    @Override
    public String toString()
    {
        return getString();
    }

    public static PhoneId getId(Context ctx, String id) {
        return (id != null && id.length() > 0) ? new PhoneId(id) : new PhoneId(ctx);
    }
}
